/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package cn.frank.framework.king.conf.mvc;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 目录枚举
 *
 * @author Chill
 */
@Slf4j
@Getter
@AllArgsConstructor
public enum WebMvcResourceEnum {


    PUBLIC(ResourceUtils.FILE_URL_PREFIX + System.getProperty("user.dir") + File.separator + "resources" + File.separator + "public" + File.separator),
    STATIC(ResourceUtils.FILE_URL_PREFIX + System.getProperty("user.dir") + File.separator + "resources" + File.separator + "static" + File.separator),
    UPLOAD(ResourceUtils.FILE_URL_PREFIX + System.getProperty("user.dir") + File.separator + "upload" + File.separator),
    // TEST_PUBLIC("D:\\MyWork\\db\\gitee\\frank\\monkey\\config\\public\\u3u8\\1\\2\\3\\"),
    // TEST_PUBLIC2("D:\\MyWork\\db\\gitee\\frank\\monkey\\config\\public\\u3u8\\1\\"),
    ;


    /**
     * 获取路径
     */
    final String path;

    public String getSimplePath() {
        return find("");
    }

    public String getOriginalPath() {
        return this.path;
    }

    /**
     * 初始化创建目录,不存在则创建
     */
    public void init() {
        if (isRunningInIDE()) return;
        String path = find("");
        String menuPath = path.startsWith(ResourceUtils.FILE_URL_PREFIX) ? path.replace(ResourceUtils.FILE_URL_PREFIX, "") : path;
        File menu = new File(menuPath);
        if (!menu.exists()) {
            menu.mkdirs();
        }
    }

    /**
     * 清空目录,[cleanMenu]=true会删除目录
     */
    public void clean(boolean cleanMenu) {
        String path = find("");
        try {
            Files.walk(new File(path).toPath())
                    .sorted(java.util.Collections.reverseOrder())
                    .map(Path::toFile)
                    .forEach(file -> {
                        if (file.isDirectory()) {
                            if (cleanMenu && !StrUtil.equals(file.getPath(), new File(path).getPath())) {
                                file.delete();
                            }
                        } else {
                            try {
                                Files.delete(file.toPath());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取追加[child]的子目录
     */
    public String find(String child) {
        String path = this.path;
        if (path.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
            path = path.replace(ResourceUtils.FILE_URL_PREFIX, "");
        }
        File menu = new File(path + child);
        if (!menu.exists()) {
            menu.mkdirs();
        }
        return path + child;
    }

    /**
     * 判断是否idea开发工具启动
     * @return
     */
    public static boolean isRunningInIDE() {
        String cp = System.getProperty("java.class.path", "").toLowerCase(); // 转为小写便于比较
        String cmd = System.getProperty("sun.java.command", "").toLowerCase();

        // 检查是否在 IntelliJ IDEA 中运行
        boolean isIdea = cp.contains("idea"); // 注意：idea.active 可能不总是可靠

        // VS Code 判断（红帽 Java 插件 / .vscode 路径）
        boolean isVsCode = cp.contains("redhat.java") || cp.contains(".vscode");

        // Cursor 判断（通过 CURSOR_* 环境变量识别）
        boolean isCursor = System.getenv().keySet().stream().anyMatch(k -> k.startsWith("CURSOR_"));

        log.info("isIdea={} isVsCode={} isCursor={}",isIdea,isVsCode,isCursor);
        return isIdea || isVsCode || isCursor;
    }
    public static void main(String[] args) {
        // WebAutoMvcResourceEnum.TEST_PUBLIC.init();
        // WebAutoMvcResourceEnum.TEST_PUBLIC2.clean(true);
        // WebAutoMvcResourceEnum.TEST_PUBLIC2.find("55/66");
    }

}
